package main

import (
	"flag"
	"fmt"
	"html/template"
	"net/http"
	"strings"
	"time"
	"websocket/server"
)

var addrs = flag.String("addr", ":8050", "http service address")
var secret = flag.String("secret", "", "push secret Keys")
var manager = flag.String("manager", "admin", "operate secret Keys")
var receiveUrl = flag.String("receive", "", "receive message url")

func home(w http.ResponseWriter, r *http.Request) {
	homeTemplates.Execute(w, fmt.Sprintf("ws://"+r.Host+"/ws?group=666&bindingID=%v", time.Now().UnixNano()/1e6))
}

var hub *server.Hub

func main() {
	flag.Parse()
	fmt.Println(*addrs)
	fmt.Println("manager：", *manager)

	// 消息转发中心
	hub = server.NewHub()
	go hub.Run()

	// 消息回调通知指定服务器
	var dispense *server.Dispense
	if len(*receiveUrl) > 0 {
		dispense = server.NewDispense(*receiveUrl)
		go dispense.Run()
	}

	// 推送权限验证与处理
	var secrets []string
	var secretManager *server.SecretManager
	secrets = strings.Split(*secret, ",")
	secretManager = server.NewSecretManager(*manager, secrets)
	go secretManager.Run()
	fmt.Println("secret：", secrets)

	// 接收一个请求，进行操作secret
	http.HandleFunc("/secret", func(writer http.ResponseWriter, request *http.Request) {
		server.Secret(secretManager, writer, request)
	})

	// 把客户端进来的连接升级为websocket连接
	http.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) {
		server.ServeWs(hub, dispense, writer, request)
	})
	// 接收一个请求，进行推送消息
	http.HandleFunc("/push", func(writer http.ResponseWriter, request *http.Request) {
		server.GroupPush(hub, secretManager, writer, request)
	})

	// js demo页面
	http.HandleFunc("/", home)
	err := http.ListenAndServe(*addrs, nil)
	if err != nil {
		panic(err)
		return
	}
	fmt.Println("执行结束")
}

var homeTemplates = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>  
window.addEventListener("load", function(evt) {

    var output = document.getElementById("output");
    var input = document.getElementById("input");
    var ws;

    var print = function(message) {
        var d = document.createElement("div");
        d.textContent = message;
        output.appendChild(d);
    };

    document.getElementById("open").onclick = function(evt) {
        if (ws) {
            return false;
        }
        ws = new WebSocket("{{.}}");
        ws.onopen = function(evt) {
            print("OPEN");
        }
        ws.onclose = function(evt) {
            print("CLOSE");
            ws = null;
        }
        ws.onmessage = function(evt) {
            print("接收: " + evt.data);
        }
        ws.onerror = function(evt) {
            print("ERROR: " + evt.data);
        }
        return false;
    };

    document.getElementById("send").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        print("SEND: " + input.value);
        ws.send('{"type":"message","content":"'+input.value+'"}');
        return false;
    };

    document.getElementById("close").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        ws.close();
        return false;
    };

});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server, 
"Send" to send a message to the server and "Close" to close the connection. 
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>
<p><input id="input" type="text" value="Hello world!">
<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output"></div>
</td></tr></table>
</body>
</html>
`))

// 启动一个端口监听
// 根据客户端连接升级协议，支持websocket
// 需要地方保存这个客户端
// 需要一个地址接受推送
